//定义js命名空间
Ext.namespace('Infrastructure.InfraHospUser');
//TODO : 完善数据结构
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//InfraUser FieldArray
Infrastructure.InfraHospUser.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'Name', type: 'string' },
	{ name: 'LoginName', type: 'string' },
	{ name: 'Pwd', type: 'string' },
	{ name: 'Code', type: 'string' },
	{ name: 'Mobitl', type: 'string' },
	{ name: 'Hometl', type: 'string' },
	{ name: 'Offitl', type: 'string' },
	{ name: 'Shortl', type: 'string' },
	{ name: 'DepartmentId', type: 'string' },
	{ name: 'Department.Name', mapping: 'Department.Name' },
	{ name: 'Department.Code', mapping: 'Department.Code' },
	{ name: 'UserGroup', type: 'string' },
	{ name: 'PostId', type: 'string' },
	{ name: 'Description', type: 'string' },
	{ name: 'InputCode1', type: 'string' },
	{ name: 'InputCode2', type: 'string' },
	{ name: 'InputCode3', type: 'string' },
	{ name: 'Description', type: 'string' },
	{ name: 'Createtime', type: 'date' },
	{ name: 'Isdelete', type: 'bool' },
	{ name: 'Version', type: 'int' },
	{ name: 'State', type: 'string' }
);

//InfraUser JsonReader
Infrastructure.InfraHospUser.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.InfraHospUser.JsonReader.superclass.constructor.call(this, Ext.apply({
			fields: Infrastructure.InfraHospUser.BaseFieldsArray
		}, cfg));
	}
});

//InfraUser JsonStore
Infrastructure.InfraHospUser.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.InfraHospUser.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/InfraHospUser/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: Infrastructure.InfraHospUser.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/InfraHospUser/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
			}
		}, cfg));
	}
});

//Infrastructure.InfraHospUser.UserStateStore
Infrastructure.InfraHospUser.UserStateStore = Ext.extend(Ext.data.JsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		Infrastructure.InfraHospUser.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/InfraHospUser/GetState',
			id: 'Value',
			fields: ['Key', 'Value']
		}, cfg));
	}
});

//InfraUser GridPanel
Infrastructure.InfraHospUser.GridPanel = Ext.extend(Infrastructure.BaseGridPanel, {
	// Property
	baseUrl: '/InfraHospUser/',
	store: new Infrastructure.InfraHospUser.JsonStore(),

	//constructor
	initComponent: function () {
		//prepare

		var itemGrid = this;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onQueryList;
		var userFunc = this.onUserFunc;

		// The filter.
		var gridFilter = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'UserId', type: 'string' },
				{ dataIndex: 'Name', type: 'string' },
				{ dataIndex: 'LoginName', type: 'string' },
				{ dataIndex: 'Pwd', type: 'string' },
				{ dataIndex: 'Code', type: 'string' },
				{ dataIndex: 'Mobitl', type: 'string' },
				{ dataIndex: 'Hometl', type: 'string' },
				{ dataIndex: 'Offitl', type: 'string' },
				{ dataIndex: 'Shortl', type: 'string' },
				{ dataIndex: 'Department.Name', type: 'string' },
				{ dataIndex: 'UserGroup', type: 'string' },
				{ dataIndex: 'PostId', type: 'string' },
				{ dataIndex: 'Description', type: 'string' },
				{ dataIndex: 'InputCode1', type: 'string' },
				{ dataIndex: 'InputCode2', type: 'string' },
				{ dataIndex: 'InputCode3', type: 'string' },
				{ dataIndex: 'Createtime', type: 'string' },
				{ dataIndex: 'Isdelete', type: 'string' },
				{ dataIndex: 'Version', type: 'string' },
				{ dataIndex: 'State', type: 'string' }
			]
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			header: '',
			singleSelect: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					itemGrid.delBtn.setDisabled(sm.getCount() < 1);
				}
			}
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				{ header: "用户名称", dataIndex: 'Name' },
				{ header: "登录名", dataIndex: 'LoginName' },
				{ header: "代码", dataIndex: 'Code' },
				{ header: "手机号码", dataIndex: 'Mobitl', width: 80 },
				{ header: "家庭电话", dataIndex: 'Hometl', width: 70 },
				{ header: "办公电话", dataIndex: 'Offitl', width: 70, hidden: true },
				{ header: "短号", dataIndex: 'Shortl', width: 50 },
				{ header: "机构", dataIndex: 'Department.Name', width: 40 },
				{ header: "分组", dataIndex: 'UserGroup', width: 40 },
				{ header: "职务", dataIndex: 'PostId' },
				{ header: "描述", dataIndex: 'Description', hidden: true },
				{ header: "助记码1", dataIndex: 'InputCode1', hidden: true },
				{ header: "助记码2", dataIndex: 'InputCode2', hidden: true },
				{ header: "助记码3", dataIndex: 'InputCode3', hidden: true },
				{ header: "状态", dataIndex: 'State', width: 35,
					renderer: function (v) {
						return v == "" ? "v" : InfrastructureStateStore.getById(v).get("Key");
					}
				}
			],
			defaults: {
				sortable: true,
				menuDisabled: false
			}
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		Ext.applyIf(this, {
			plugins: [gridFilter],
			sm: selModel,
			cm: gridColumn,
			tbar: [{
				xtype: 'tbaraddbtn',
				handler: cmdAddEntity,
				scope: itemGrid
			}, '-', {
				xtype: 'tbardelbtn',
				handler: cmdDeleteEntity,
				scope: itemGrid
			}, '-', {
				menuid: '',
				xtype: 'tbarmenubtn',
				ref: '../sendSms',
				text: '发送飞信邀请',
				icon: '/Content/icons/phone_sound.png',
				handler: function () {
					itemGrid.tbarSubmit('/InfraHospUser/SendFetionAddSms', '确定要发送飞信邀请短信吗?', '邀请信息发送成功。');
				},
				scope: itemGrid
			}, '-', {
				xtype: 'textfield',
				width: 150,
				id: 'q_query'
			}, {
				xtype: 'tbarqrybtn',
				handler: cmdQueryList,
				scope: itemGrid
			}, '-'],
			bbar: pagebBar,
			listeners: {
				'rowdblclick': cmdLoadEntity
			}
		});

		Infrastructure.InfraHospUser.GridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var itemEditForm = new Infrastructure.InfraHospUser.EditForm({
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						ele.form.reset();
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
						JsHelper.ShowInfo('添加信息成功!');
					}
				}
			}
		});
		var itemEditWin = new Infrastructure.InfraHospUser.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 读取信息显示
	onLoadEntity: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('请选择记录编辑..');
			return -1;
		}
		var selId = selRecord.data.Id;
		var itemEditForm = new Infrastructure.InfraHospUser.EditForm({
			Id: selId,
			waitMsg: '数据加载中...',
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						itemGrid.store.reload();
						JsHelper.ShowInfo('信息更新成功!');
					}
				}
			}
		});
		var itemEditWin = new Infrastructure.InfraHospUser.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
		itemEditForm.form.loadRecord(selRecord);
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	// 测试..
	onUserFunc: function () {
		var itemGrid = this;
		alert('UserFunc....');
	}
});

//InfraHospUser EditForm
Infrastructure.InfraHospUser.EditForm = Ext.extend(Infrastructure.BaseForm, {
	Id: null,
	SaveUrl: '/InfraHospUser/SaveOrUpdate',
	reader: new Infrastructure.InfraHospUser.JsonReader(),

	initComponent: function () {
		var itemEditForm = this;
		var cmdUpdate = this.onSave;
		var UpdateEdit = (this.Id != null);

		//Form第一列
		// 定义表单列
		var firstColumn = [{
			fieldLabel: '登录名<span style="color: red;" >*</span>',
			width: 150,
			maxLength: 10,
			xtype: 'textfield',
			readOnly: UpdateEdit,
			name: 'LoginName',
			rvOptions: {
				url: '/InfraHospUser/IsFieldExist',
				params: {
					'Id': this.Id,
					'FieldName': 'LoginName'
				}
			},
			plugins: [Ext.ux.plugins.RemoteValidator]

		}, {
			fieldLabel: '用户名称<span style="color: red;" >*</span>',
			width: 150,
			maxLength: 10,
			xtype: 'textfield',
			disable: UpdateEdit,
			name: 'Name'
		}, {
			fieldLabel: '代码<span style="color: red;" >*</span>',
			width: 150,
			maxLength: 10,
			xtype: 'textfield',
			readOnly: UpdateEdit,
			name: 'Code',
			rvOptions: {
				url: '/InfraHospUser/IsFieldExist',
				params: {
					'Id': this.Id,
					'FieldName': 'Code'
				}
			},
			plugins: [Ext.ux.plugins.RemoteValidator]
		}, {
			fieldLabel: "所在机构",
			width: 150,
			xtype: 'deptcombo',
			hiddenName: 'DepartmentId',
			name: 'DepartmentId'
		}, {
			fieldLabel: "所属分组",
			width: 150,
			maxLength: 36,
			allowBlank: true,
			xtype: 'dictcombo',
			category: 'CompGroup',
			name: 'UserGroup'
		}, {
			fieldLabel: "职务",
			width: 150,
			maxLength: 36,
			xtype: 'dictcombo',
			category: 'UserPost',
			name: 'PostId'
		}, {
			fieldLabel: '用户状态<span style="color: red;" >*</span>',
			width: 150,
			xtype: 'basecombo',
			name: 'State',
			hiddenName: 'State',
			store: InfrastructureStateStore,
			valueField: 'Value',
			displayField: 'Key'
		}];

		if (!UpdateEdit) {
			firstColumn = [firstColumn, {
				fieldLabel: '密码<span style="color: red;" >*</span>',
				inputType: 'password',
				id: 'Infra_HospUser_pass_Pwd',
				allowBlank: false,
				width: 150,
				maxLength: 16,
				name: 'Pwd'
			}, {
				fieldLabel: '验证密码<span style="color: red;" >*</span>',
				inputType: 'password',
				allowBlank: false,
				width: 150,
				maxLength: 16,
				name: 'Pwdcfrm',
				vtype: 'password',
				initialPassField: 'Infra_HospUser_pass_Pwd'
			}];
		};

		//Form第二列
		var secondColumn = [{
			fieldLabel: "手机号码",
			width: 150,
			maxLength: 20,
			xtype: 'textfield',
			name: 'Mobitl'
		}, {
			fieldLabel: "家庭电话",
			width: 150,
			maxLength: 20,
			xtype: 'textfield',
			name: 'Hometl'
		}, {
			fieldLabel: "办公电话",
			width: 150,
			maxLength: 20,
			xtype: 'textfield',
			name: 'Offitl'
		}, {
			fieldLabel: "短号",
			width: 150,
			maxLength: 20,
			xtype: 'textfield',
			name: 'Shortl'
		}, {
			fieldLabel: "助记码1",
			width: 150,
			maxLength: 255,
			xtype: 'textfield',
			name: 'InputCode1'
		}, {
			fieldLabel: "助记码2",
			width: 150,
			maxLength: 255,
			xtype: 'textfield',
			name: 'InputCode2'
		}, {
			fieldLabel: "助记码3",
			width: 150,
			maxLength: 255,
			xtype: 'textfield',
			name: 'InputCode3'
		}];

		//Form单列
		var singleColumn = [{
			xtype: 'textarea',
			fieldLabel: '描述',
			name: 'Description',
			height: 50,
			width: 430
		}];

		Ext.apply(this, {
			items: [{
				layout: 'column',
				// 注意 现在使用的是两列 要是三列或更多
				// 请改变下面的items
				// 并在上面定义每个列的组件集合
				items: [{
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: firstColumn
				}, {
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: secondColumn
				}]
			}, singleColumn],
			buttons: [
					new Ext.ux.SubmitBtn({
						handler: cmdUpdate,
						scope: itemEditForm
					}),
					new Ext.ux.CancelBtn({
						handler: function () {
							itemEditForm.ownerCt.destroy();
						}
					})
			]
		});

		Infrastructure.InfraHospUser.EditForm.superclass.initComponent.call(this);
		this.addEvents('afterSave');
	},

	/****************** 
	* user function 
	******************/

	//保存
	onSave: function () {
		var itemForm = this;
		var id = this.Id;
		var saveUrl = this.SaveUrl;
		if (itemForm.getForm().isValid()) {
			itemForm.getForm().submit({
				waitMsg: '正在提交数据....',
				url: saveUrl,
				params: {
					'Id': (id == null) ? '' : id
				},
				success: function (form, action) {
					//保存后刷新表格
					itemForm.fireEvent('afterSave', itemForm, true);
				},
				failure: function (form, action) {
					JsHelper.ShowError(action.result.msg);
				}
			});
		}
	}
});

//InfraUser DetailWin
Infrastructure.InfraHospUser.EditWin = Ext.extend(Ext.Window, {
	title: 'InfraUser Infomation',
	iconCls: 'application_form',
	width: 600,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',

	//constructor
	initComponent: function () {
		Infrastructure.InfraHospUser.EditWin.superclass.initComponent.call(this);
	}
});
